package com.malou.client.reportes;

import java.util.HashMap;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Status;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Frame;
import com.malou.client.MalouConstants;

public class PdfReportViewer extends FormPanel {
	private Frame frame;
	private MalouConstants constants = GWT.create(MalouConstants.class);
	public PdfReportViewer(String fileName, HashMap<String, Object> param, final Status status, final Button find, final Button print, final Integer consulta_id){
		setLayout(new FitLayout());
		//setHeading(title);
		setFrame(true);
		setHeaderVisible(false);
		frame = new Frame();
		add(frame);
		
		AsyncCallback<String> reportURLCallback = new AsyncCallback<String>(){
			
			MessageBox messageBox = new MessageBox();

			@Override
			public void onFailure(Throwable caught) {
				messageBox.setMessage(constants.errorConexion());
				messageBox.show();
				caught.printStackTrace();
				if(status != null)	status.hide();				
				if(find != null)	find.show();
			}

			@Override
			public void onSuccess(String result) {
				if (result != null){					
					frame.setUrl(result);					
				}else{
					messageBox.setMessage(constants.noSePudoCargarReporte());
					messageBox.show();
				}
				if(status != null)	status.hide();				
				if(find != null)	find.show();
				if(print != null)	print.setEnabled(true);				
			}
			
		};
		
		((ReporteServiceAsync) GWT.create(ReporteService.class)).getPdfReport(fileName, param, consulta_id, reportURLCallback);
		if(print != null){
			SelectionListener<ButtonEvent> sl_print;        
	        sl_print = new SelectionListener<ButtonEvent>(){
	        	
	        	@Override
				public void componentSelected(ButtonEvent ce) {				
					showPrintDialog(frame.getElement());				
				}
	        };
	        print.removeAllListeners();
	        print.addSelectionListener(sl_print);
		}
	}
	public native boolean showPrintDialog(Element element) /*-{ 
		if ($wnd.print) { 
		   //$wnd.print();		   
		    element.contentWindow.print();		    
		   return true; 
		} else { 
		   return false; 
		}  
	}-*/; 
}
